package com.scwatch.core.web.back.f7;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.scwatch.common.util.Dates;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Info;
import com.scwatch.core.domain.Model;
import com.scwatch.core.service.InfoQueryService;
import com.scwatch.core.service.ModelService;
import com.scwatch.core.support.Context;
import com.scwatch.core.thirdapi.UserSystemApi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by gjl on 2018/3/13.
 */
@Controller
@RequestMapping("/ext/info")
public class InfoF7Controller {

    @RequestMapping("chooseRelatednews.do")
    public String chooseRelatednews(HttpServletRequest request, HttpServletResponse response,
                                   org.springframework.ui.Model modelMap,String param,String relateNews) throws IOException {
        modelMap.addAttribute("infoId",param);
        modelMap.addAttribute("relateNews",relateNews);
        return "ext/info/info_choose_relatednews";
    }

    @RequestMapping("getChoiceRelatednews.do")
    @ResponseBody
    public Object getChoiceRelatednews(HttpServletRequest request, HttpServletResponse response,
                                 @PageableDefault(sort = {"priority","publishDate"}, direction = Sort.Direction.DESC) Pageable pageable,
                                 String title,String startTime,String endTime,String infoId,String idsdata,String isChoice) throws IOException {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);

        List<Integer> infoIdList=new ArrayList<>();
        Map<Integer, Integer> jsonMap=new HashMap<>();
        if(StringUtils.isNotBlank(idsdata)){
            jsonMap = JSON.parseObject(idsdata, new TypeReference<HashMap<Integer,Integer>>(){});
            //将map.entrySet()转换成list
            List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(jsonMap.entrySet());

            for (Map.Entry<Integer, Integer> mapping : list) {
                infoIdList.add(mapping.getKey());
            }

        }

        List<Info> infos=query.findAll(infoIdList);
        List<JSONObject> listJson=new ArrayList<>();
        int count=0;
        if(infos!=null && infos.size()>0){
            JSONObject jsonObject=null;
            for(Info info:infos){
                jsonObject =new JSONObject();
                if(info!=null){
                    count++;
                    jsonObject.put("id",info.getId());
                    jsonObject.put("title",info.getTitle()==null?"":info.getTitle());
                    jsonObject.put("nodeName",info.getNode().getName()==null?"":info.getNode().getName());
                    jsonObject.put("priority",info.getPriority());
                    jsonObject.put("status",info.getStatus());
                    jsonObject.put("publishDate", Dates.formatDate(info.getPublishDate(),"yyyy-MM-dd HH:mm:ss"));
                    jsonObject.put("sort",jsonMap.get(info.getId()));
                    listJson.add(jsonObject);
                }

            }
        }

        Collections.sort(listJson, new Comparator<JSONObject>() {
            //降序排序
            @Override
            public int compare(JSONObject o1,JSONObject o2) {
                Integer sort1 = o1.getInteger("sort") == null ? 0 : o1.getInteger("sort");
                Integer sort2 = o2.getInteger("sort") == null ? 0 : o2.getInteger("sort");
                Integer priority1 = o1.getInteger("priority");
                Integer priority2 = o2.getInteger("priority");
                Date pubDate1 = o1.getDate("publishDate");
                Date pubDate2 = o2.getDate("publishDate");

                int result=0;
                if (sort1 != null && sort2 != null) {
                    result= sort2.compareTo(sort1);
                }
                if(priority1 != null && priority2 != null && result==0){
                    result=priority2.compareTo(priority1);
                }
                if(pubDate1 !=null && pubDate2 !=null && result==0){
                    result=pubDate2.compareTo(pubDate1);
                }
                return  result;
            }
        });
        JSONObject o=new JSONObject();
        o.put("totalElements",count);
        o.put("totalPages",1);
        o.put("content",listJson);
        return o;
    }

    @RequestMapping("getRelatednews.do")
    @ResponseBody
    public Object getRelatednews(HttpServletRequest request, HttpServletResponse response,
                                    @PageableDefault(sort = {"priority","publishDate"}, direction = Sort.Direction.DESC) Pageable pageable,
                                    String title,String startTime,String endTime,String infoId,String idsdata) throws IOException {
        Integer siteId = Context.getCurrentSiteId();
//        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);

        List<Integer> infoIdList=new ArrayList<>();
        Map<Integer, Integer> jsonMap=new HashMap<>();
        if(StringUtils.isNotBlank(idsdata)){
            jsonMap = JSON.parseObject(idsdata, new TypeReference<HashMap<Integer,Integer>>(){});
            //将map.entrySet()转换成list
            List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(jsonMap.entrySet());
            for (Map.Entry<Integer, Integer> mapping : list) {
                infoIdList.add(Integer.valueOf(mapping.getKey()));
            }

        }
        if(StringUtils.isNotBlank(infoId)){
            infoIdList.add(Integer.valueOf(infoId));
        }
        Integer[] idstrings = new Integer[infoIdList.size()];
        infoIdList.toArray(idstrings);
//        params.put("NOTEQ_id",idstrings);
//        params.put("CONTAIN_detail.title",new String[]{title});
//        params.put("GTE_publishDate_Date",new String[]{startTime});
//        params.put("LTE_publishDate_Date",new String[]{endTime});

//        params.put("NOTEQ_id",new String[]{infoId});

        Integer[] modelIds = null;
        //只查新闻类型的新闻
        Map<String, String[]> paramMap = new HashMap<String, String[]>();
        paramMap.put("EQ_flag", new String[]{Constants.MODEL_FLAG_DOC_NEWS});
        List<Model> modelList = modelService.findList(siteId, null, paramMap, null);
        if (modelList != null && modelList.size() > 0) {
            modelIds = new Integer[modelList.size()];
            for (int i = 0; i < modelList.size(); i++) {
                modelIds[i] = modelList.get(i).getId();
            }
        }

        String[] titles=null;
        if(StringUtils.isNotBlank(title)){
            titles=new String[]{"%"+title+"%"};
        }
//        Page<Info> pagedList = query.findAll(modelIds, siteId, null, null, null,null, true,
//                1,"A", params, pageable, null);

        Page<Info> pagedList = query.findPage(modelIds,null,null,
                null, null,new Integer[]{siteId},null,null, null,
                null,null, null, null, null,
                null , null,titles, null,idstrings,
                null, null, null,new String[]{"A"},null, null,
                null, null, null, null, null, null, pageable,null,null,null,null);

        List<Info> list=pagedList.getContent();
        JSONArray jsonArray=new JSONArray();
        if(list!=null && list.size()>0){
            JSONObject jsonObject=null;
            for(Info info:list){
                jsonObject =new JSONObject();
                jsonObject.put("id",info.getId());
                jsonObject.put("title",info.getTitle()==null?"":info.getTitle());
                jsonObject.put("nodeName",info.getNode().getName()==null?"":info.getNode().getName());
                jsonObject.put("priority",info.getPriority());
                jsonObject.put("status",info.getStatus());
                jsonObject.put("publishDate", Dates.formatDate(info.getPublishDate(),"yyyy-MM-dd HH:mm:ss"));
                jsonArray.add(jsonObject);
            }
        }
        JSONObject o=new JSONObject();
        o.put("totalElements",pagedList.getTotalElements());
        o.put("totalPages",pagedList.getTotalPages());
        o.put("content",jsonArray);
        return o;
    }

    @RequestMapping("selectProductPage.do")
    public String selectProductPage(String param,HttpServletRequest request, org.springframework.ui.Model modelMap) {
        modelMap.addAttribute("productCode",param);
        return "ext/advertisement/ad_choose_productCode";
    }

    @RequestMapping("getProducts.do")
    @ResponseBody
    public JSONObject getProducts(Pageable pageable,String name) {
        UserSystemApi userSystemApi = new UserSystemApi();
        Map<String,Object> map = new HashMap<>();
        map.put("pageIndex",pageable.getPageNumber()==0?1:pageable.getPageNumber());
        map.put("productId",null);
        map.put("productName",name==null?"":name);
        JSONObject jsonObject = userSystemApi.selectProductList(map);
        JSONObject result = new JSONObject();
        result.put("totalElements",jsonObject.getJSONObject("data").get("total"));
        result.put("totalPages",jsonObject.getJSONObject("data").get("pages"));
        result.put("content",jsonObject.getJSONObject("data").get("records"));
        return result;
    }

    @Autowired
    private InfoQueryService query;
    @Autowired
    private ModelService modelService;
}
